const express = require('express')
const router = express.Router()
const User = require('../models/UserModel')
const md5 = require('blueimp-md5')
router.post('/login', async (req, res, next) => {
  try {
    let user = await User.findOne({
      nickname: req.body.nickname,
      password: md5(md5(req.body.password)) 
    })
    if (!user) {
      return res.status(200).json({
        err_code: 1,
        message: '信息错误',
      })
    }                             

    req.session.user = user
    res.status(200).json({
      err_code: 0,
      message: 'Ok',
      session: req.session.user
    })
  } catch (err) {
    next(err)
  }
})

router.post("/register",async (req, res, next) => {
  // 1.获取表单提交数据
  // 2.操作数据库判断用户是否存在，不存在则新建用户
  // 3.发送响应
  let body = req.body;
  try {
    if(await User.findOne({email: body.email})) {
      return res.status(200).json({
        err_code: 1,
        message: '邮箱存在'
      })
    }
    if(await User.findOne({nickname: body.nickname})) {
      return res.status(200).json({
        err_code: 2,
        message: '昵称存在'
      })
    }
    // 对密码加密
    body.password = md5(md5(body.password))
    //注册 
    let user = await new User(body).save()
    //注册成功，使用session记录登录状态
    req.session.user = user
    res.status(200).json({
      err_code: 0,
      message: 'Ok'
    })
  } catch (err) {
   next(err)
  }
});


module.exports = router